﻿using System.Globalization;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OpenWaves.Video.Web.Controls
{
    public class VideoThumbnail : WebControl
    {
        public string VideoUrl
        {
            get { return (string)this.ViewState["VideoUrl"] ?? string.Empty; }
            set { this.ViewState["VideoUrl"] = value; }
        }

        public new int Width
        {
            get { return (int)(this.ViewState["Width"] ?? 0); }
            set { this.ViewState["Width"] = value; }
        }

        public new int Height
        {
            get { return (int)(this.ViewState["Height"] ?? 0); }
            set { this.ViewState["Height"] = value; }
        }

        public new string CssClass
        {
            get { return (string)(this.ViewState["CssClass"] ?? string.Empty); }
            set { this.ViewState["CssClass"] = value; }
        }


        protected override void Render(HtmlTextWriter writer)
        {
            
            var videoInfo = ServiceLocator.Resolve<IVideoWebsiteApi>().GetVideo(this.VideoUrl);

            if(videoInfo == null)
            {
                return;
            }
            
            writer.AddAttribute(HtmlTextWriterAttribute.Width,
                                new Unit(this.Width, UnitType.Pixel).ToString(CultureInfo.InvariantCulture));
            writer.AddAttribute(HtmlTextWriterAttribute.Height,
                                new Unit(this.Height, UnitType.Pixel).ToString(CultureInfo.InvariantCulture));

            if (this.CssClass != string.Empty)
            {
                writer.AddAttribute(HtmlTextWriterAttribute.Class, this.CssClass);
            }


            writer.AddAttribute(HtmlTextWriterAttribute.Src, videoInfo.GetThumbnailForSize(Width, Height).Url);

            writer.RenderBeginTag(HtmlTextWriterTag.Img);
            
            writer.RenderEndTag();
        }
    }
}